﻿using DelonixRegia.Classes;
using DelonixRegia.Classes.Rooms;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DelonixRegia
{
    public partial class RoomBooking : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            tbxCheckIn.Text = DateTime.Now.ToString();

            if (!Page.IsPostBack)
            {
                string roomNo = Request.QueryString["roomNo"];

                if (!string.IsNullOrEmpty(roomNo))
                {
                    tbxRoomNumber.Text = roomNo;

                    tbxFirstName.Enabled = true;
                    tbxLastName.Enabled = true;
                    tbxContact.Enabled = true;
                    tbxEmail.Enabled = true;
                    tbxAddress.Enabled = true;
                    tbxCheckOut.Enabled = true;
                    cldCheckout.Enabled = true;
                    tbxNRIC.Enabled = true;

                    ddlCardType.Enabled = true;
                    tbxCardholderName.Enabled = true;
                    tbxCardNo.Enabled = true;
                    ddlExpiryMonth.Enabled = true;
                    ddlExpiryYear.Enabled = true;
                    tbxCSC.Enabled = true;

                    btnBook.Enabled = true;
                    btnClear.Enabled = true;

                    ClientScriptMgr.Execute("$('#cphMain_tbxFirstName').focus();$('html, body').animate({ scrollTop: $('#cphMain_tbxFirstName').offset().top }, 700);");
                }
            }
        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            if ((!string.IsNullOrEmpty(tbxNoAdult.Text)) && (!string.IsNullOrEmpty(tbxNoChildren.Text)))
            {
                tbxRoomNumber.Text = "";

                tbxFirstName.Enabled = false;
                tbxLastName.Enabled = false;
                tbxContact.Enabled = false;
                tbxEmail.Enabled = false;
                tbxAddress.Enabled = false;
                tbxCheckOut.Enabled = false;
                cldCheckout.Enabled = false;
                tbxNRIC.Enabled = false;

                ddlCardType.Enabled = false;
                tbxCardholderName.Enabled = false;
                tbxCardNo.Enabled = false;
                ddlExpiryMonth.Enabled = false;
                ddlExpiryYear.Enabled = false;
                tbxCSC.Enabled = false;

                btnBook.Enabled = false;
                btnClear.Enabled = false;

                SqlCommand comm = new SqlCommand();
                comm.CommandText = "SELECT * FROM Room WHERE (roomNo NOT IN (SELECT roomNo FROM RoomBooking WHERE bookingID NOT IN (SELECT bookingID FROM RoomCheckout))) AND capacity >= @capacity";
                comm.Parameters.AddWithValue("@capacity", (int.Parse(tbxNoAdult.Text) + int.Parse(tbxNoChildren.Text)));

                IEnumerable<Room> availableRooms = RoomDBManager.getAvailableRoom(comm);
                ArrayList list = new ArrayList();

                foreach (Room r in availableRooms)
                {
                    ViewRoom vr = new ViewRoom();
                    vr.RoomNumber = r.roomNo;
                    vr.RoomLevel = r.roomLevel;
                    vr.RoomType = RoomDBManager.getRoomType(r.roomType).name;
                    vr.RoomRate = r.roomRate;
                    list.Add(vr);
                }

                gvResult.Visible = true;
                gvResult.DataSource = list.Cast<ViewRoom>();
                gvResult.DataBind();
            }
            else
                ClientScriptMgr.showErrorBox("You need to enter the number of <i>adults</i> and <i>children</i>! If none, enter 0.");
        }

        protected void btnSelect_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            tbxRoomNumber.Text = btn.Attributes["roomNo"];

            for (int i = 0; i < gvResult.Rows.Count; i++)
            {
                gvResult.Rows[i].Attributes.Remove("class");
            }

            gvResult.Rows[int.Parse(btn.Attributes["row"])].Attributes["class"] = "success";

            tbxFirstName.Enabled = true;
            tbxLastName.Enabled = true;
            tbxContact.Enabled = true;
            tbxEmail.Enabled = true;
            tbxAddress.Enabled = true;
            tbxCheckOut.Enabled = true;
            cldCheckout.Enabled = true;
            tbxNRIC.Enabled = true;

            ddlCardType.Enabled = true;
            tbxCardholderName.Enabled = true;
            tbxCardNo.Enabled = true;
            ddlExpiryMonth.Enabled = true;
            ddlExpiryYear.Enabled = true;
            tbxCSC.Enabled = true;

            btnBook.Enabled = true;
            btnClear.Enabled = true;

            ClientScriptMgr.Execute("$('#cphMain_tbxFirstName').focus();$('html, body').animate({ scrollTop: $('#cphMain_tbxFirstName').offset().top }, 700);");
        }

        protected void gvResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                e.Row.Cells[1].Text = "Room Number";
                e.Row.Cells[2].Text = "Level";
                e.Row.Cells[3].Text = "Room Type";
                e.Row.Cells[4].Text = "Room Rate";
            }

            GridViewRow gvr = (GridViewRow)e.Row;

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Button btn = (Button)gvr.FindControl("btnSelect");         
                int roomNo = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "RoomNumber"));
                btn.Attributes.Add("roomNo", roomNo.ToString());
                btn.Attributes.Add("row", e.Row.RowIndex.ToString());
            }
        }

        protected void cldCheckout_SelectionChanged(object sender, EventArgs e)
        {
            tbxCheckOut.Text = cldCheckout.SelectedDate.ToString();
        }

        protected void cldCheckout_DayRender(object sender, DayRenderEventArgs e)
        {
            if (e.Day.Date <= DateTime.Now.Date)
            {
                e.Day.IsSelectable = false;
                e.Cell.ForeColor = System.Drawing.Color.Gray;
            }
        }

        protected void btnBook_Click(object sender, EventArgs e)
        {
            Classes.RoomBooking book = new Classes.RoomBooking();
            PaymentDetail pd = new PaymentDetail();

            pd.cardType = ddlCardType.SelectedItem.Text;
            pd.cardholderName = tbxCardholderName.Text;
            pd.cardNo = tbxCardNo.Text;
            pd.expiryDate = ddlExpiryMonth.SelectedItem.Text + "/" + ddlExpiryYear.SelectedItem.Text;
            pd.securityCode = int.Parse(tbxCSC.Text);

            book.firstName = tbxFirstName.Text;
            book.lastName = tbxLastName.Text;
            book.contactNo = tbxContact.Text;
            book.emailAddress = tbxEmail.Text;
            book.address = tbxAddress.Text;
            book.checkIn = Convert.ToDateTime(tbxCheckIn.Text);
            book.checkOut = Convert.ToDateTime(tbxCheckOut.Text);
            book.nric = tbxNRIC.Text;

            book.noOfAdults = int.Parse(tbxNoAdult.Text);
            book.noOfChildren = int.Parse(tbxNoChildren.Text);

            book.roomNo = int.Parse(tbxRoomNumber.Text);
            book.paymentDetails = pd;

            if (RoomBookingDBManager.Book(book))
            {
                pnlFirstStep.Visible = false;
                pnlSecondStep.Visible = true;
                Page.ClientScript.RegisterStartupScript(GetType(), "transitionToSecondStep", "transitionToSecondStep();", true);
            }
            else
            {
                ClientScriptMgr.showErrorBox("Unable to book room, pls try again later.");
            }
        }

        protected void btnGoBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("Default.aspx");
        }
    }
}